package digitenjoyDubboUtils;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author whj
 * @Description 查询高德实时天气信息
 * @Date 2021/7/6 11:06
 */
public class WeatherUtil {

    /**
     *  高德地图申请调用接口的key值地址: https://console.amap.com/dev/key/app
     * 下面为个人测试key值
     */
    private static final String weatherKey = "9488f5ada4a25cc4f4e615791f176b54";

    /**
     * 查询天气信息
     * @return
     */
    public static Map queryWeather() {
        Map<String,String> param1 = new HashMap<>(2);
        param1.put("key",weatherKey);
        param1.put("address","浙江省绍兴市");
        try {
            //获取地理位置
            String result = HttpClientUtil.doGet("https://restapi.amap.com/v3/geocode/geo", param1);
            Map<String,Object> resultMap = JSON.parseObject(result);
            Object dataObject = resultMap.get("geocodes");
            String adCode = null;
            List<Map> lists = JSON.parseArray(JSON.toJSONString(dataObject), Map.class);
            Map map = lists.get(0);
            adCode = map.get("adcode").toString();
            //请求天气数据
            Map<String, String> params2 = new HashMap<>();
            params2.put("key",weatherKey);
            params2.put("city",adCode);
            String result2 = HttpClientUtil.doGet("https://restapi.amap.com/v3/weather/weatherInfo", params2);
            Map<String,Object> resultMap2 = JSON.parseObject(result2);
            Object lives = resultMap2.get("lives");
            List<Map> infos = JSON.parseArray(JSON.toJSONString(lives), Map.class);
            return infos.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap();
    }

    public static void main(String[] args) {
        Map map = WeatherUtil.queryWeather();
        System.out.println(map.toString());
    }
}
